<?php

/*
 * 微商城登录控制器
 * @author <!-- blakefan 1621743934@qq.com -->
 * 
 */

namespace Home\Controller;
use Think\Controller;
class LoginController extends Controller
{
	

	/*
	 *微商城登录页面
	 */
	public function index()
	{
        if(!empty($_SESSION['uid']))
        {
        	$this->redirect('Index/index');
        }else
        {
        	 $this->display('index');
        }

	}
	/*
	 *验证用户名密码
	 *@param 用户名，密码
	 *return json
	 */
	public function verifyUser()
	{
		$result='';
		$username=I('post.username','','strip_tags');
		$password=I('post.password','','strip_tags');
		$where['uname']=trim($username);
		$user=M('user');
		$userinfo=$user->where($where)->getField('uid,pass');
		//用户不存在
		$key=key($userinfo);
		if(empty($key))
			{
				$result['status']=0;
				$result['msg']='用户名或密码错误';
				echo json_encode($result);
				return '';
			};
		//用户密码错误
		$pass=md5(trim($password));
		
		if(current($userinfo)!==$pass)
		{
			$result['status']=0;
			$result['msg']='密码错误';
			echo json_encode($result);
			return '';
		}

		if(current($userinfo)===$pass)
		{
			//将用户信息写入session
			$_SESSION['uid']=key($userinfo);
			$result['status']=1;
			$result['msg']='success';
			echo json_encode($result);
			return '';
		}
	}
	/*
	 *注册用户
	 */
	public function resister()
	{
		$this->display();
		
	}
	/*
	 *保存用户
	 */
	public function saveUser(){

		$result='';
		$uname=I('post.uname','','strip_tags');
		$pass=I('post.pass','','strip_tags');
		$pid=I('post.pid',0,'strip_tags');
		$user=M('user');
		$temp=$user->where("uname='%s'",$uname)->count();
		if(!empty($temp))
		{
			$result['status']=2;
			$result['msg']='用户名已存在';
			echo json_encode($result);
			return '';
		}
		$user->create();
		$user->addtime=time();
		$user->openid=!empty($_SESSION['openid'])?$_SESSION['openid']:''; //微信openid
		$user->nickname=!empty($_SESSION['nickname'])?$_SESSION['nickname']:''; //微信昵称
		$user->pid=$pid;
		$user->pass=md5($pass);
		$user->uname=$uname;
		$uid=$user->add();
		if($uid !==false)
		{
			//将uid 保存到session 中
			$_SESSION['uid']=$uid;
			$result['status']=1;
			$result['msg']='success';
			echo json_encode($result);
			return '';
		}
		$result['status']=0;
		$result['msg']='系统繁忙，请稍后再试';
		echo json_encode($result);
		return '';
	}

}